import { createWebHistory, createRouter } from 'vue-router'
import Layout from '@/views/layout/index.vue'
const modules = import.meta.glob('@/views/**/*.vue')
const modulesKeys = Object.keys(modules)

//#region基础路由
const routes = [
    { path: '/404', name: '404', component: () => import("@/views/404.vue") },
]
// #endregion

const router = createRouter({
    history: createWebHistory(),
    routes,
})



//#region 注册路由
const routerList = [
    { path: '/news', name: 'News', meth: { title: '新闻' }, url: '@/views/News/index.vue' },
    { path: '/index', name: 'Index', meth: { title: '首页' }, url: '@/views/Index/index.vue' },
]
const init = async () => {
    routerList.forEach(item => {
        const index = modulesKeys.findIndex(itemUrl => itemUrl.includes(item.url.split('views/')[1]))
        if (index !== -1) {
            router.addRoute({
                path: '', component: Layout, children: [
                    {
                        path: item.path,
                        name: item.name,
                        component: modules[modulesKeys[index]],
                    }
                ]
            })
        }
    })
    router.replace(window.location.pathname)
}
init()
// #endregion



// #region 路由守卫
router.beforeEach((to, from, next) => {
    if (to.matched.length === 0) {
        // 路由不存在，可以重定向到404页面
        next('/404')
    } else {
        next()
    }
})
// #endregion

export default router